package cn.wyl.user.service.impl;

import cn.wyl.basic.exception.BusinessException;
import cn.wyl.basic.jwt.JwtUtils;
import cn.wyl.basic.jwt.RsaUtils;
import cn.wyl.basic.util.*;
import cn.wyl.system.domain.Menu;
import cn.wyl.user.constant.WxConstants;
import cn.wyl.user.domain.Logininfo;
import cn.wyl.user.domain.User;
import cn.wyl.user.domain.Wxuser;
import cn.wyl.user.dto.LoginData;
import cn.wyl.user.mapper.LogininfoMapper;
import cn.wyl.user.mapper.UserMapper;
import cn.wyl.user.mapper.WxuserMapper;
import cn.wyl.user.service.ILogininfoService;
import cn.wyl.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> accountLogin(Map loginMap) {
        String phone = (String)loginMap.get("phone");
        String password = (String)loginMap.get("password");
        Integer type = (Integer) loginMap.get("type");

        Logininfo logininfo1 = new Logininfo();
        logininfo1.setPhone(phone);
        logininfo1.setType(type);



        //1.校验
        //1.1.空值校验
        if(StringUtils.isEmpty(phone) ||StringUtils.isEmpty(password) )
        {
            throw new BusinessException("请输入合法信息!!!");
        }

        Logininfo logininfo = logininfoMapper.loadByAccount(logininfo1);
        if(logininfo == null){
            throw  new BusinessException("用户名或密码错误!!!");
        }
        //1.2.用户名或密码【加密加盐】校验
        String dbMd5Pwd = logininfo.getPassword();
        String md5Pwd = Md5Utils.encrypByMd5( logininfo.getSalt()+password);
        if(!dbMd5Pwd.equals(md5Pwd)){
            throw new BusinessException("用户名或密码错误!!!");
        }

        //1.3.状态校验 - 启用，禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("你的账号被冻结，请联系管理员!!!");
        }

        // 登录成功后redis存储token,loginfo并返回给前端
        /*//2.将token和登录信息对象 保存在 redis 30分钟有效
        String token = UUID.randomUUID().toString();
        //logininfo必须序列化才能存入redis
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        //3.使用Map封装token和登录对象
        //说明：token相当于jessionid   登录对象响应到前端 - 在系统中回显用户名
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/

        //jwt实现将 loginfo,menus,permissions,jwttoken(loginfo,menus,permissions用私钥加密后得到的字符串)放入map中，并返回前端
        //后端不存这些值
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;

    }

    /**
     * 微信登录业务,通过code获取token和openid
     * 通过openid去t_wxuser中查询
     * 有绑定过 - 直接免密登录 获取logininfo对象 登录
     * 没有 - 需要跳转页面绑定 - 响应给前端进行跳转
     * @param code
     * @return
     */
    @Override
    public AxiousResult wechatLogin(String code) {

        //1.根据code发送请求获取token和openid
        String url = WxConstants.GET_ACK_URL
                .replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        //后端借助HttpUtil发送get请求 返回内容 json字符串
        //{"access_token":"57_3R0PHzOIKX6brh1TbBZKqwsOCHugjzrJeDZgssoAmsF_UFOq-TSTXE3tmZBUr7VIZ_eP71LhIzOeLeh4gua3vVligjDuBCjRiImEAPSAwqc","openid":"oa9wA01X4TNik8bbXWklIyArUZ5c",}
        String jsonStr =HttpUtil.httpGet(url);

        //2.将响应的json字符串 转成 json对象
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");


        //3.通过openid去t_wxuser中查询
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);

        //绑定过，直接免密登录【获取logininfo对象 登录】
        if (wxuser!=null&&wxuser.getUser_id()!=null){
            Logininfo logininfo=logininfoMapper.loadbyUserId(wxuser.getUser_id());

            /*//生成token，相当于浏览器缓存的登录信息id,将token和登录信息对象 保存在 redis 30分钟有效
            String token = UUID.randomUUID().toString();
            //logininfo必须序列化才能存入redis
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            //去掉密码和盐值 - 安全
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            //使用Map封装token和登录对象
            //说明：token相当于jessionid   登录对象响应到前端 - 在系统中回显用户名
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo",logininfo);
            return new AxiousResult(true,"成功",map);*/
            Map<String, Object> map = loginSuccessJwtHandler(logininfo);
            return new AxiousResult(true,"成功",map);

        }else { // 没绑定过，给前端返回一个携带access_token，openid参数的对象，因为接下来要根据access_token，openid访问微信平台获取wxuser绑定注册
            Map<String, Object> map = new HashMap<>();
            map.put("access_token",access_token);
            map.put("openid",openid);
            return new AxiousResult(false,"失败",map);

        }

    }

    @Override
    public AxiousResult wechatBinder(Map<String, Object> paramsMap) {
        String phone = (String)paramsMap.get("phone");
        String verifyCode = (String)paramsMap.get("verifyCode");
        String accessToken = (String)paramsMap.get("accessToken");
        String openId = (String)paramsMap.get("openId");
        //校验
        //1.校验 - 空置校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("电话号或验证码不能为空");
        }
        //2.校验 - 验证码是否过期  //code:1215215155
        Object redisCode = redisTemplate.opsForValue().get(VerifyCodeConstants.BINDER_PREFIX + phone);
        if (redisCode==null){
            throw new BusinessException("验证码过期或无效");
        }
        //3.校验 - 验证码是否正确
        if (!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode.trim())){
            throw new BusinessException("验证码错误");
        }

        //绑定用户：t_wxUser【user_id】 绑定 t_user 绑定t_logininfo
        //4.获取WxUser - 发送第三个请求携带accessToken openId - 返回json字符串
        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);

        //后端通过HttpUtil工具类发送get请求
        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser=jsonStr2Wxuser(jsonStr);

        //微信绑定user注册
        //通过phone查询User
        User user = userMapper.loadByPhone(phone);
        //如果没有 - 根据phone创建User对象 - 创建Logininfo对象 - 保存Logininfo对象 - 保存User对象
        if (user==null){
            user = phone2User(phone);
            Logininfo logininfoTmp= user2Logininfo(user);
            logininfoMapper.save(logininfoTmp);
            user.setLogininfo_id(logininfoTmp.getId());
            userMapper.save(user);
        }
        //将User对象的id设置到WxUser对象中
        wxuser.setUser_id(user.getId());
        //将WxUser对象添加到数据库
        wxuserMapper.save(wxuser);

        //免密登录
        Logininfo logininfo = logininfoMapper.loadbyUserId(user.getId());

       /* String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);

        Map<String, Object> map = new HashMap<>();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("token",token);
        map.put("logininfo",logininfo);
        return new AxiousResult(true,"成功",map);*/
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return new AxiousResult(true,"成功",map);

    }

    @Override
    /**
     * 根据token删除redis中Key为token的记录
     */
    public AxiousResult loginout(String token) {
        Object logininfo = redisTemplate.opsForValue().get(token);
        if (logininfo!=null){
            try {
                redisTemplate.delete(token);
                return new AxiousResult(true,"成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
      throw  new BusinessException("redis异常");
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(user.getState()==1?true:false);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机的纯数据密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(salt+randomPwd );
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        //将json字符串解析成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname("unknown");
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }

    /**
     * 1.获取logininfo
     * 2.获取当前登陆人的所有权限 - sn
     * 3.获取当前登陆人的所有菜单 - 【难度】
     * 4.通过私钥对登录信息进行加密 - jwtToken串
     * 5.转到map返回
     * @param logininfo
     * @return
     */
    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        //创建LoginData对象用于等会通过私钥加密
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();
        try {
            //1.获取logininfo
            if(logininfo.getType()==0){//管理员
                //2.获取当前登陆人的所有权限 - sn
                List<String> permissions = logininfoMapper.loadPermissionsByLogininfoId(logininfo.getId());
                //3.获取当前登陆人的所有菜单 - 【难度】
                List<Menu> menus = logininfoMapper.loadMenusByLogininfoId(logininfo.getId());
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);
                //将当前登陆人的权限和菜单添加到map - 响应给前端
                map.put("permissions",permissions);
                map.put("menus",menus);
            }
            //4.通过私钥对登录信息进行加密 - jwtToken串
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader()
                                                                        .getResource("auth_rsa.pri").getFile());
            //将登陆人信息加密得到jwtToken串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300);
            //5.装到map返回
            map.put("token",jwtToken);
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



}
